var myID = null;
$(document).ready(function(){
	$("#chatIframe").attr("style","height:"+(document.body.scrollHeight-180)+"px;");
	$.ajax({url:"getMyID",
		success:function(result){
			myID = result;
		}
	});
	$.ajax({url:"init",
		data:{
			yourId:sessionStorage.getItem("stu_id")
		},
		success:function(result){
			for(var i=result.length -1;i>=0;i--){
				showGreeting(result[i]);
			}
		}
	});
})
var stompClient = null;
function connect(){
    var socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({},function (frame){
        stompClient.subscribe('/user/queue/chat',function (message) {
            showGreeting(JSON.parse(message.body));
        });
    });
}
function sendMsg() {
    stompClient.send("/app/chat",{},
        JSON.stringify({'content':$("#content").val(),'to_id':sessionStorage.getItem("stu_id")}));
    $("#content").val("");
}
function showGreeting(message) {
	if(message.from_id==myID){
		var $div = $("<div></div>");
		$div.attr("id","charRow");
		var $divTemp=$("<div>"+message.from_name+":"+message.content+"</div>");
		$divTemp.attr("id","chatBox1");
		$div.append($divTemp);
		$("#chatContent").append($div);
		
	}
	else{
		var $div = $("<div></div>");
		$div.attr("id","charRow");
		var $divTemp=$("<div>"+message.from_name+":"+message.content+"</div>");
		$divTemp.attr("id","chatBox2");
		$div.append($divTemp);
		$("#chatContent").append($div);
	}
}
$(function () {
    connect();
    $("#send").click(function () {
        sendMsg();
    })
});